package com.ceadeal.javafxboot.util;

import com.arcsoft.face.FaceFeature;
import com.arcsoft.face.FaceInfo;
import com.ceadeal.javafxboot.config.TowerGuardConfig;
import com.ceadeal.javafxboot.entity.FaceUserInfo;
import com.ceadeal.javafxboot.mapper.FaceUserInfoMapper;
import com.ceadeal.javafxboot.service.IArcSoftService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.function.Consumer;

@Slf4j
@Component
public class FaceHelper {
    @Autowired
    TowerGuardConfig towerGuardConfig;
    @Autowired
    IArcSoftService arcSoftService;
    @Autowired
    FaceUserInfoMapper faceUserInfoMapper;
    private List<FaceUserInfo> faceUserInfos;
    /**
     * 获取文件后缀的方法
     *
     * @param file 要获取文件后缀的文件
     * @return 文件后缀
     * @author https://www.4spaces.org/
     */
    String getFileExtension(File file) {
        String extension = "";
        try {
            if (file != null && file.exists()) {
                String name = file.getName();
                extension = name.substring(name.lastIndexOf("."));
            }
        } catch (Exception e) {
            extension = "";
        }
        return extension;
    }

    /**
     * 获取文件名，不包括文件按扩展名
     * @param file
     * @return
     */
    String getFileNameWithoutExtension(File file) {
        String pureName = "";
        try {
            if (file != null && file.exists()) {
                String name = file.getName();
                pureName = name.substring(0,name.lastIndexOf("."));
            }
        } catch (Exception e) {
            pureName = "";
        }
        return pureName;
    }

    /**
     * 将配置文件中指定路径下图片的人脸数据进行识别并保存到数据库红
     * @throws InterruptedException
     */
    public void registerFaces() throws InterruptedException {
        File fileDirectory = new File(towerGuardConfig.getNewFaceImagePath());        //获取其file对象
        registerFaces(fileDirectory);
    }

    public List<FaceInfo> detectFaces(File file){
        return arcSoftService.detectFaces(file);
    }

    public void registerFaces(File fileDirectory) throws InterruptedException {
        File[] fs = fileDirectory.listFiles();    //遍历path下的文件和目录，放在File数组中
        for (File file : fs) {                    //遍历File[]数组
            if (!file.isDirectory() && ".jpg".equals(getFileExtension(file)))        //若非目录(即文件)，则打印
            {
                List<FaceFeature> faceFeatures = arcSoftService.extractFaceFeature(file);
                if (faceFeatures != null && faceFeatures.size() > 0) {
                    String personName = getFileNameWithoutExtension(file);
                    System.out.println("检测到人脸数据：" + personName);
                    if (faceUserInfoMapper.getPersonCount(personName)!=0)
                    {
                        FaceUserInfo faceUserInfo = FaceUserInfo.builder().name(personName).face_feature(faceFeatures.get(0).getFeatureData()).build();
                        faceUserInfoMapper.insertFaceInfo(faceUserInfo);//添加到数据库
                        //拷贝到存档文件夹
                        backFile(file);
                    }
                    else{
                        System.out.println("人员已经存在数据库中："+personName);
                    }

                }
            }

        }
    }

    /**
     * 备份文件到软件设置的目录下
     * @param file
     */
    private void backFile(File file) {
        try{
            String newPath = towerGuardConfig.getBackFaceImagePath()+"/"+ file.getName();
            FileOutputStream fsOut = new FileOutputStream(newPath);
            Files.copy(file.toPath(),fsOut);
        }
        catch (IOException e)
        {
            System.out.println("拷贝文件错误");
        }
    }


    /**
     * 加载人脸数据到缓存中
     */
    public void loadFaceUserInfos()
    {
        faceUserInfos = faceUserInfoMapper.selectAllFaceInfos();
    }

    public void compareFace(File jpegs, Consumer<List<FaceUserInfo>> consumer) throws InterruptedException, ExecutionException {
        //计数器
        long num = 0;
        String threadName="mainwindow";
        Long startTime = System.currentTimeMillis();
        List<FaceFeature> faceFeatures = arcSoftService.extractFaceFeature(jpegs);
        log.debug("线程：{}，resp帧比对，第：{} 次，匹配人脸数：{}", threadName, num, faceFeatures.size());
        if (!CollectionUtils.isEmpty(faceFeatures)) {
            for (int i = 0; i < faceFeatures.size(); i++) {
//                log.debug("线程：{}，resp帧比对，第：{} 次，开始第{}张人脸查找", threadName, num, i + 1);
                List<FaceUserInfo> compareFaces = arcSoftService.compareFaceFeature(faceFeatures.get(i), faceUserInfos, 100);
//                log.debug("线程：{}，resp帧比对，第：{} 次，结束第{}张人脸查找,匹配人脸数：{}", threadName, num, i + 1, compareFaces.size());
                //匹配到的人脸执行业务处理
                consumer.accept(compareFaces);
                System.out.println("对比完毕");
            }
        }
        log.debug("线程：{}，resp帧比对，第：{} 次结束,耗时：{}毫秒", threadName, num, System.currentTimeMillis() - startTime);

    }
}
